//
//  WSADManager.m
//  CharonTVProject
//
//  Created by karong on 2023/8/1.
//

#import "WSADManager.h"
#import <GoogleMobileAds/GoogleMobileAds.h>

@interface WSADManager () <GADFullScreenContentDelegate>
@property (nonatomic, strong) GADRewardedAd * rewardedAd;
@end

@implementation WSADManager
SingletonM

- (instancetype)init {
    self = [super init];
    if (self) {
        self.onlineTimePlayVideoToday = [appUserDefaults integerForKey:@"kOlineTimePlayVideoToday"] == [NSDate new].day;
    }
    return self;
}

- (void)resetOnlineTimePlayVideoTodayState:(BOOL)state {
    self.onlineTimePlayVideoToday = state;
    if (state) {
        [appUserDefaults setInteger:[NSDate new].day forKey:@"kOlineTimePlayVideoToday"];
        [appUserDefaults synchronize];
    }
}

///谷歌广告
- (void)loadRewardedAd {
  GADRequest *request = [GADRequest request];
  [GADRewardedAd
       loadWithAdUnitID:WS_GOOGLE_TASKAD_KEY
                request:request
      completionHandler:^(GADRewardedAd *ad, NSError *error) {
        if (error) {
            NSLog(@"Rewarded ad failed to load with error: %@", [error localizedDescription]);
#warning 上架時要註釋掉這個toast
            [WSToast simple:[error localizedDescription]];
            return;
        }
        self.rewardedAd = ad;
        NSLog(@"Rewarded ad loaded.");
        self.rewardedAd.fullScreenContentDelegate = self;
        [self showADView];
      }];
}

- (void)showADView{
    if (self.rewardedAd && [self.rewardedAd canPresentFromRootViewController:[WSTools currentViewController].navigationController error:nil]) {
        [self.rewardedAd presentFromRootViewController:[WSTools currentViewController].navigationController
                              userDidEarnRewardHandler:^{
            GADAdReward *reward = self.rewardedAd.adReward;
            NSString *rewardMessage = [NSString
                                       stringWithFormat:@"Reward received with currency %@ , amount %lf",
                                       reward.type, [reward.amount doubleValue]];
            NSLog(@"%@", rewardMessage);
            if ([self.delegate respondsToSelector:@selector(rewardVideoPlayComplete:)]) {
                [self.delegate rewardVideoPlayComplete:self];
            }
            // Reward the user for watching the video.
        }];
    }
}

/// Tells the delegate that the ad failed to present full screen content.
- (void)ad:(nonnull id<GADFullScreenPresentingAd>)ad
    didFailToPresentFullScreenContentWithError:(nonnull NSError *)error {
    NSLog(@"Ad did fail to present full screen content.");
}

- (void)adDidRecordImpression:(nonnull id<GADFullScreenPresentingAd>)ad{
    NSLog(@"展示成功");
    if ([self.delegate respondsToSelector:@selector(rewardVideoPlayComplete:)]) {
        [self.delegate rewardVideoPlayComplete:self];
    }
}


@end
